package com.ibm.workplace.wcm.cqplugin.ui.views;


import org.eclipse.core.runtime.*;
import org.eclipse.core.runtime.Preferences.*;
import org.eclipse.core.runtime.jobs.*;
import org.eclipse.jface.preference.*;
import org.eclipse.swt.*;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.dialogs.*;
import org.eclipse.ui.part.*;

import com.ibm.workplace.wcm.cqplugin.*;
import com.ibm.workplace.wcm.cqplugin.composites.BugInfoViewComposite;
import com.ibm.workplace.wcm.cqplugin.preference.BugInfoPreferenceConstants;
import com.ibm.workplace.wcm.cqplugin.ui.IProgressPresenter;
import com.ibm.workplace.wcm.cqplugin.ui.preference.*;

public class CQBugInfoView extends ViewPart implements SelectionListener, ControlListener, IPropertyChangeListener, IBugSearchListener, IProgressPresenter {

    private static CQBugInfoView instance;

    private BugInfoViewComposite bugViewComposite;
    private Composite welcomeComposite;
    private StackLayout stackLayout;

    public CQBugInfoView() {
        super();

        instance = this;

        Activator.getDefault().getPluginPreferences().addPropertyChangeListener(this);
    }

    public void dispose() {
        Activator.getDefault().getPluginPreferences().removePropertyChangeListener(this);

        super.dispose();
    }

    public void createPartControl(Composite parent) {
        Composite c = new Composite(parent, 0);
        stackLayout = new StackLayout();
        stackLayout.marginHeight = 0;
        stackLayout.marginWidth = 0;
        c.setLayout(stackLayout);

        bugViewComposite = new BugInfoViewComposite(c, 0);
        welcomeComposite = createWelcome(c);

        //comment out to skip welcome
        boolean showWelcome = !Activator.getDefault().getPreferenceStore().getBoolean(BugInfoPreferenceConstants.PREF_SETTINGS_CONFIGURED);
        setWelcomeVisible(showWelcome);
    }

    public static CQBugInfoView getInstance() {
        return instance;
    }

    /* public static void refresh() {
     if (instance != null) {
     if (instance.bugViewComposite != null) {
     Display.getDefault().asyncExec(new Runnable() {
     public void run() {
     instance.bugViewComposite.refresh();
     }
     });
     }
     }
     }
     */

    public void setFocus() {
        if (stackLayout != null && stackLayout.topControl == bugViewComposite) {
            stackLayout.topControl.setFocus();
        }
    }

    public void refreshQueryList(final String defaultQuery) {
        if (instance != null) {
            if (instance.bugViewComposite != null) {
                Display.getDefault().asyncExec(new Runnable() {

                    public void run() {
                        instance.bugViewComposite.populateQueryList();
                        instance.bugViewComposite.selectQuery(defaultQuery);
                    }
                });
            }
        }
    }

    public void refreshQueryList() {
        refreshQueryList(null);
    }

    public void refresh() {
        if (instance != null) {
            if (instance.bugViewComposite != null) {
                Display.getDefault().asyncExec(new Runnable() {

                    public void run() {
                        instance.bugViewComposite.refresh();
                    }
                });
            }
        }
    }

    /*public void setBugSearchResults(final IBugInfo[] bugs, final IBugSearchCriteria searchCriteria) {
        if (instance.bugViewComposite != null) {
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    instance.bugViewComposite.setBugSearchResults(bugs, searchCriteria);
                }
            });
        }
    }*/

    protected Composite createWelcome(Composite parent) {
        welcomeComposite = new Composite(parent, 0);
        GridLayout layout = new GridLayout(1, false);
        welcomeComposite.setLayout(layout);

        welcomeComposite.setBackground(parent.getDisplay().getSystemColor(SWT.COLOR_LIST_BACKGROUND));
        welcomeComposite.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_LIST_FOREGROUND));

        Link l = new Link(welcomeComposite, SWT.WRAP);
        l.setText("To start, configure your <a>CQ preferences</a>.");
        l.addSelectionListener(this);
        l.setBackground(welcomeComposite.getBackground());

        welcomeComposite.addControlListener(this);

        return welcomeComposite;
    }

    public void widgetDefaultSelected(SelectionEvent arg0) {

    }

    public void widgetSelected(SelectionEvent event) {
        if (event.getSource() instanceof Link) {
        	// Comment Out to avoid error
        	
        	//PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(getSite().getShell(), CqPreferencePage.class.getName(), new String[] { CqPreferencePage.class.getName(), AdvancedPreferencesPage.class.getName() }, null);
        	PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(getSite().getShell(), CqPreferencePage.class.getName(), new String[] { CqPreferencePage.class.getName() }, null);
            dialog.open();
            
        }
    }

    public void controlMoved(ControlEvent event) {
        // TODO Auto-generated method stub        
    }

    public void controlResized(ControlEvent event) {
        if (event.getSource() == welcomeComposite) {
            Link l = (Link) welcomeComposite.getChildren()[0];
            GridData data = (GridData) l.getLayoutData();
            if (data != null) {
                data.widthHint = welcomeComposite.getBounds().width;
            }
        }
    }

    public void propertyChange(PropertyChangeEvent event) {
    	
    	if (event.getSource() == Activator.getDefault().getPluginPreferences()) {
            if (event.getProperty().equals(BugInfoPreferenceConstants.PREF_SETTINGS_CONFIGURED)) {

                try {
                    Boolean b = Boolean.valueOf(event.getNewValue().toString());
                    setWelcomeVisible(!b.booleanValue());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                //                /Boolean val = (Boolean)event.getNewValue();
                //setWelcomeVisible(!val.booleanValue());
            }
        }

    }

    private void setWelcomeVisible(boolean visible) {
        if (visible) {
            stackLayout.topControl = welcomeComposite;
            welcomeComposite.getParent().layout(true);
        } else {
            stackLayout.topControl = bugViewComposite;
            bugViewComposite.getParent().layout(true);
            
            // Comment Out to avoid error
            /*
            String defaultQueryName = BugInfoPluginActivator.getDefault().getPreferenceStore().getString(BugInfoPreferenceConstants.PREF_PREVIOUS_QUERY);
            if (defaultQueryName == null || defaultQueryName.trim().equals("")) {
                bugViewComposite.selectQuery(0); // select the first query (My open defects)    
            } else {
                bugViewComposite.selectQuery(defaultQueryName);
            }
            */
            
        }
    }
      
    public void setProgressVisible(boolean visible) {
        if (bugViewComposite != null) bugViewComposite.setProgressVisible(visible);
    }
    
    public void setProgress(int percent) {
        if (bugViewComposite != null) bugViewComposite.setProgress(percent);    
    }   
    
    public void setProgressStatusText(String text) {
        if (bugViewComposite != null) bugViewComposite.setProgressStatusText(text);
    }
    
    // Comment Out to avoid error

    public void bugSearchComplete(final IBugSearchResults bsr) {
    	if(Activator.DEBUG_ON)
    		System.out.println("bugSearchComplete");
        if (bugViewComposite != null) {
        	if(Activator.DEBUG_ON)
        		System.out.println("bugViewComposite!=null");
            Display.getDefault().asyncExec(new Runnable() {
                public void run() {
                    bugViewComposite.bugSearchComplete(bsr);
                }
            });            
        }        
    }
    
    private PerformBugSearchJob currentBugSearchJob;
	
    public PerformBugSearchJob performSearch(final IBugQuery query) {
    	if(Activator.DEBUG_ON)
    		System.out.println("enter performSearch()");
        
    	final IBugSearchListener bugSearchListener = this;
        final IProgressPresenter progressPresenter = this;

        // This should not be done this way - it prevents a query from being run when an incoming chat message appears
        if (currentBugSearchJob != null && (currentBugSearchJob.getState() == Job.RUNNING || currentBugSearchJob.getState() == Job.WAITING)) {
            currentBugSearchJob.cancel();
        }
        
        final long startTime = System.currentTimeMillis();

        PerformBugSearchJob job = new PerformBugSearchJob(query, this);
        job.addJobChangeListener(new JobChangeAdapter() {

            public void done(IJobChangeEvent event) {
            	if(Activator.DEBUG_ON)
            		System.out.println("JobChangeAdapter.done()");
                if (event.getResult() == Status.OK_STATUS) {  
                	if(Activator.DEBUG_ON)
                		System.out.println("Status.OK_STATUS");
                    BugSearchResults bsr = new BugSearchResults(((PerformBugSearchJob)event.getJob()).getResults(), query, System.currentTimeMillis() - startTime);
                    bugSearchListener.bugSearchComplete(bsr);                    
                } else {
                    progressPresenter.setProgressStatusText(null);
                }
            }
            
        });

        currentBugSearchJob = job;

        job.setUser(true);
        job.setPriority(Job.LONG);
        job.schedule();

        return job;
    }
    

    public PerformBugSearchJob getCurrentBugSearchJob() {
        return currentBugSearchJob;
    }


}